/**
 * @file utils/request
 * @author maoquan(maoquan@htsc.com)
 */

import 'whatwg-fetch';
import { notification } from 'antd';
import config from '../config/request';
notification.config({
	placement: 'topRight',
	duration: 5,
});
/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
	return response.json().then(
		(res) => {
			// 神策的响应是succeed: true
			const { code, msg, succeed, status, message } = res;
			// code == '0' &&  msg == 'ok' !succeed
			// console.log('global tip', res);
			// if (+code === 1) {
			// 	// return res;
			// 	throw new Error(msg);

			// }
			if (+status == 403) {

				

				throw new Error(message);


				// window.location.href = `${location.href.split('#')[0]}#/login`;
			}

			if (code === '0' && msg === 'ok') {
				let error;
				if (code === 'MAG0010') {
					// 这里使用code作为message，以便对登录错误做特殊处理
					error = new Error(code);
				} else {
					error = new Error(msg);
				}
				throw error;

			}
			if(msg&&msg!='OK'){
				notification.error({
					message: msg
				});
			}
			
			return res;
		},
	);
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response;
	}
	// 未登录
	if (response.status === 403) {
		const from=window.location.href.split('#')[1]
		if(from.indexOf('/login')===-1){
			localStorage.from=from.split('&_k=')[0].split('?_k=')[0]
		}
		location.href=location.href.split("#")[0]+"#/login"
		window.location.reload()
		return response;
	}
	// 用户名密码错误
	if (response.status === 401) {
		return response;
	}

	if (response.status === 500 ) {
		throw new Error("服务器异常！");
	}

	const error = new Error(response.statusText);
	error.response = response;
	throw error;
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options) {
	return Promise.race([
		fetch(url, { credentials: 'include', ...options })
			.then(checkStatus)
			.then(parseJSON),
		new Promise(
			(rosolve, reject) => {// eslint-disable-line
				setTimeout(
					() => reject('请求超时'),
					config.timeout,
				);
			},
		),
	]);
}
